<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <PageTool>
        <!-- vue2.6前写法,只针对一个标签,slot="插槽名" -->
        <span slot="before">共有{{ page.total }}条数据</span>
        <!-- vue2.6之后写法,v-slot:插槽名, 简写# -->
        <template #after>
          <el-button type="danger" @click="handleDownload">Excel导出</el-button>
          <el-button type="success" @click="$router.push('/import')">Excel导入</el-button>
          <el-button type="primary" @click="showAddDialog=true">新增员工</el-button>
        </template>
      </PageTool>

      <el-card v-loading="loading">
        <el-table :data="list" border stripe>
          <el-table-column label="序号" :sortable="true" type="index" width="50"></el-table-column>
          <el-table-column label="姓名" :sortable="true" prop="username"></el-table-column>
          <el-table-column label="头像" :sortable="true" prop="staffPhoto" width="150">
            <template v-slot="{row}">
              <!-- 当返回图片错误时,显示默认图片-方式1 -->
              <!-- <img v-imgerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" style="width:100px;height:100px;border-radius:50%"> -->

              <!-- 当返回图片错误时,显示默认图片-方式2 -->
              <el-image :src="row.staffPhoto" style="width:100px;height:100px;border-radius:50%" @click="onShowQrcodeDialog(row.staffPhoto)">
                <img slot="error" src="@/assets/common/head.jpg" style="width:100px;height:100px;border-radius:50%" @click="onShowQrcodeDialog(require('@/assets/common/head.jpg'))">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="手机号" :sortable="true" prop="mobile"></el-table-column>
          <el-table-column label="工号" :sortable="true" prop="workNumber"></el-table-column>
          <el-table-column label="聘用形式" :sortable="true" prop="formOfEmployment">
            <template v-slot="{row}"> {{ row.formOfEmployment | formathireType }} </template>
          </el-table-column>
          <el-table-column label="部门" :sortable="true" prop="departmentName"></el-table-column>
          <el-table-column label="入职时间" :sortable="true" prop="timeOfEntry">
            <template v-slot="{row}"> {{ row.timeOfEntry | formatdate }} </template>
          </el-table-column>
          <el-table-column label="账户状态" :sortable="true" prop="enableState">
            <template v-slot="{row}">
              <!-- 后端返回的enableState为数字类型,所以active-value和inactive-value控制开关状态的属性也要为数字类型,前面加:就可以改变接收的是数字 -->
              <!-- 总结: 如果接口返回的status是数字类型的，需要加上动态绑定 -->
              <el-switch
                v-model="row.enableState"
                disabled
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" :sortable="true" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="onDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end">
          <el-pagination
            layout="total, prev, pager, next"
            :page-size="page.size"
            :total="page.total"
            @current-change="onPageChange"
          >
          </el-pagination>
        </el-row>
      </el-card>
    </div>

    <!-- 显示二维码弹框 -->
    <el-dialog title="显示二维码" :visible.sync="showQrcodeDialog">
      <el-row type="flex" justify="center">
        <qrcode-vue :value="staffPhotoUrl" class="qrimg"></qrcode-vue>
      </el-row>
    </el-dialog>
    <!-- 新增员工弹框 -->
    <el-dialog :visible="showAddDialog" v-bind="$attrs" title="新增员工" v-on="$listeners" @open="onOpen" @close="close">
      <el-form ref="formRef" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入姓名" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="入职时间" prop="timeOfEntry">
          <el-date-picker
            v-model="form.timeOfEntry"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :style="{width: '100%'}"
            placeholder="请选择入职时间"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="聘用形式" prop="formOfEmployment">
          <el-select v-model="form.formOfEmployment" placeholder="请选择聘用形式" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in formOfEmploymentOptions"
              :key="index"
              :label="item.value"
              :value="item.id"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工号" prop="workNumber">
          <el-input v-model="form.workNumber" placeholder="请输入工号" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入部门" clearable :style="{width: '100%'}" @focus="getDeptList">
          </el-input>
          <el-tree
            v-if="showTree"
            :data="depts"
            :props="{label: 'name'}"
            @node-click="onNodeClick"
          ></el-tree>
        </el-form-item>
        <el-form-item label="转正时间" prop="correctionTime">
          <el-date-picker
            v-model="form.correctionTime"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :style="{width: '100%'}"
            placeholder="请选择转正时间"
            clearable
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import employeesEnum from '@/api/constant/employees.js'
import QrcodeVue from 'qrcode.vue' // 引入二维码插件
import { addEmployee, delEmployee, getEmployees } from '@/api/employees'
import { getList } from '@/api/departments'
import { translateListToTree } from '@/utils'
import { pick } from 'lodash'
import { formatdate, formathireType } from '@/filters'
export default {
  name: 'Employees',
  components: {
    QrcodeVue
  },
  data() {
    return {
      loading: false,
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      showQrcodeDialog: false, // 二维码弹框状态
      staffPhotoUrl: undefined, // 用户头像
      form: { // 新增员工弹框表单数据
        username: undefined,
        mobile: undefined,
        timeOfEntry: null,
        formOfEmployment: undefined,
        workNumber: undefined,
        departmentName: undefined,
        correctionTime: null
      },
      rules: { // 新增员工弹框校验规则
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机', trigger: 'blur' }],
        timeOfEntry: [{ required: true, message: '请选择入职时间', trigger: 'change' }],
        formOfEmployment: [{ required: true, message: '请选择聘用形式', trigger: 'change' }],
        workNumber: [{ required: true, message: '请输入工号', trigger: 'blur' }],
        departmentName: [{ required: true, message: '请输入部门', trigger: 'change' }],
        correctionTime: []
      },
      formOfEmploymentOptions: employeesEnum.hireType, // 聘用形式下拉选项
      showAddDialog: false, // 新增员工弹框状态
      depts: [], // 部门树形数据
      showTree: false
    }
  },
  computed: {

  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.loading = true
      const { total, rows } = await getEmployees(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    onPageChange(val) {
      this.page.page = val
      this.getList()
    },
    // 展示二维码
    onShowQrcodeDialog(url) {
      this.staffPhotoUrl = url
      this.showQrcodeDialog = true
    },
    onOpen() {},
    close() {
      this.$refs['formRef'].resetFields()
      this.showAddDialog = false
    },
    // 提交新增员工
    handelConfirm() {
      this.$refs['formRef'].validate(async valid => {
        if (!valid) return
        await addEmployee(this.form)
        this.$message.success('操作成功')
        this.getList()
        this.close()
      })
    },
    // 获取部门列表数据
    async getDeptList() {
      this.showTree = true
      this.depts = translateListToTree((await getList()).depts, '')
    },
    // 点击树形组件的节点并赋值给输入框的v-model
    onNodeClick(data) {
      // data为点击节点的数据
      // 当点击节点之后，移出树形组件
      this.showTree = false
      this.form.departmentName = data.name
    },
    // 删除员工
    onDel(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        if (this.list.length === 1) {
          this.page.page -= 1
        }
        await delEmployee(id)
        this.$message.success('操作成功')
        this.getList()
      })
    },
    // excel导出
    handleDownload() {
      // 数据从哪里来? - 导出所有数据: size传参就为列表的total值
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployees({
          page: 1,
          size: this.page.total
        })
        console.log(rows)
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const data = rows.map(t => {
          // 1. 首先是从rows每个元素中过滤出headers对应的字段
          const item = pick(t, Object.values(headers))
          item.timeOfEntry = formatdate(item.timeOfEntry)
          item.correctionTime = formatdate(item.correctionTime)
          item.formOfEmployment = formathireType(item.formOfEmployment)

          // 2. 过滤后的每个元素获取其values,Object.values返回为数组,最后map返回组成的新数组
          return Object.values(item)
        })
        console.log(data)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头,必填
          data: data, // 具体数据,必填
          filename: '人资中台员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// .qrimg{
//   width: 200px;
//   height: 20px;
//   canvas {
//     width: 100%;
//     height: 100%;
//   }
// }
</style>
